<template>
    <div class="summary-container">
        <div class="summary-header">
            <img src="./img/sum.png" alt="sum" class="summary-title-img" />
            <span class="summary-title">{{ $t('summary.title') }}</span>
        </div>
        <div class="summary-table">
            <!-- <div class="summary-row summary-row-header" style="background: #f0f2f5;">
                <div class="summary-col summary-col-item">{{ $t('summary.item') }}</div>
                <div class="summary-col summary-col-af"><span style="color: #4caf50;">AF</span>{{ $t('summary.data') }}</div>
                <div class="summary-col summary-col-mf"><span style="color: #197aff;">MF</span>{{ $t('summary.data') }}</div>
            </div> -->
            <div class="summary-row" v-for="item in summaryList" :key="item.key">
                <div class="summary-col summary-col-item">
                    <img :src="item.icon" class="summary-icon" :alt="$t('summary.' + item.key)" />
                    <span class="summary-label">{{ $t('summary.' + item.key) }}</span>
                </div>
                <div class="summary-col summary-col-af">
                    <template v-if="item.key === 'target-out'">
                        <div>
                            <div>
                                <span class="af num">{{ formatBoxAndCabinet(item.af).cabinetNum }}</span>
                                <span class="unit">{{ formatBoxAndCabinet(item.af).cabinetUnit }}</span>
                            </div>
                            <div>
                                <span class="af num">{{ formatBoxAndCabinet(item.af).num }}</span>
                                <span class="unit">{{ formatBoxAndCabinet(item.af).box }}</span>
                            </div>
                        </div>
                    </template>
                    <template v-else-if="item.key === 'max-in' || item.key === 'min-in'">
                        <span v-html="formatDateNumUnit(item.af, item.key === 'min-in','af')"></span>
                    </template>
                    <template v-else>
                        <template v-if="item.key !== 'match' && item.af !== '~'">
                            <div>
                                <div>
                                    <span class="af num">{{ formatBoxAndCabinet(item.af).cabinetNum }}</span><span class="unit">{{ formatBoxAndCabinet(item.af).cabinetUnit }}</span>
                                </div>
                                <div>
                                    <span class="af num">{{ formatBoxAndCabinet(item.af).num }}</span>
                                    <span class="unit">{{ formatBoxAndCabinet(item.af).box }}</span>
                                </div>
                            </div>
                        </template>
                        <span v-else class="af num">{{ item.af }}</span>
                    </template>
                </div>
                <div class="summary-col summary-col-mf">
                    <template v-if="item.key === 'target-out'">
                        <div>
                            <div>
                                <span class="mf num">{{ formatBoxAndCabinet(item.mf).cabinetNum }}</span>
                                <span class="unit">{{ formatBoxAndCabinet(item.mf).cabinetUnit }}</span>
                            </div>
                            <div>
                                <span class="mf num">{{ formatBoxAndCabinet(item.mf).num }}</span>
                                <span class="unit">{{ formatBoxAndCabinet(item.mf).box }}</span>
                            </div>
                        </div>
                    </template>
                    <template v-else-if="item.key === 'max-in' || item.key === 'min-in'">
                        <span v-html="formatDateNumUnit(item.mf, item.key === 'min-in','mf')"></span>
                    </template>
                    <template v-else>
                        <template v-if="item.key !== 'match' && item.mf !== '~'">
                            <div>
                                <div>
                                    <span class="mf num">{{ formatBoxAndCabinet(item.mf).cabinetNum }}</span><span class="unit">{{ formatBoxAndCabinet(item.mf).cabinetUnit }}</span>
                                </div>
                                <div>
                                    <span class="mf num">{{ formatBoxAndCabinet(item.mf).num }}</span>
                                    <span class="unit">{{ formatBoxAndCabinet(item.mf).box }}</span>
                                </div>
                            </div>
                        </template>
                        <span v-else class="mf num">{{ item.mf }}</span>
                    </template>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { getDateList } from '@/api/index';
import { reactive, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

function addUnitToLastLine(str, unit) {
    // 把每个 <br> 后的数字后加单位
    return str.replace(/(\d+)(?![\s\S]*\d)/, '$1' + unit);
}

function formatDateNumUnit(str, isMinIn = false, type = '') {
    if (!str) return '~';

    let dateColor = '';
    let numberColor = '';

    if (type === 'af') {
        numberColor = '#409EFF';
    } else if (type === 'mf') {
        numberColor = '#4caf50';
    }

    // 本月最高入库日期为紫色
    if (!isMinIn && type) {
        dateColor = '#652bde';
    } else if (isMinIn) {
        dateColor = '#e74c3c';
    } else {
        dateColor = numberColor;
    }

    const dateStyle = dateColor ? `style="color: ${dateColor}"` : '';
    const numberStyle = numberColor ? `style="color: ${numberColor}"` : '';

    if (str.includes('<br>') || str.includes('|')) {
        const parts = str.includes('<br>') ? str.split('<br>') : str.split('|');
        const datePart = parts[0].slice(5);
        let num = parts[1] ? Math.round(parseFloat(parts[1])) : '';

        if (!num) {
            return `<span ${dateStyle} class="${type} num">${datePart}</span><br>~`;
        }
        const cabinet = (num*28);
        return `<span ${dateStyle} class="${type} num">${datePart}</span><br><div><div><span ${numberStyle} class="${type} num">${cabinet}</span><span class="unit">${t('unit.box2') || '盒'}</span></div><div><span ${numberStyle} class="${type} num">${num}</span><span style='margin-left:4px' class="unit">${t('unit.box')}</span></div></div>`;
    }
    return str;
}

function formatBoxAndCabinet(val) {
    // 只处理数字
    const num = Number(val);
    if (isNaN(num) || val === '~') return { num: val, box: '', cabinetNum: '', cabinetUnit: '' };
    const cabinet = (num*28);
    return {
        num: num,
        box: t('unit.box'),
        cabinetNum: cabinet,
        cabinetUnit: t('unit.box2') || '盒'
    };
}

const summaryList = reactive([
    {
        key: 'target-out',
        label: '出库目标',
        icon: new URL('./img/e1.png', import.meta.url).href,
        af: '0',
        mf: '0',
    },
    {
        key: 'out',
        label: '累计出库',
        icon: new URL('./img/e3.png', import.meta.url).href,
        af: '0',
        mf: '0',
    },
    {
        key: 'target-in',
        label: '入库目标',
        icon: new URL('./img/e2.png', import.meta.url).href,
        af: '0',
        mf: '0',
    },
    {
        key: 'in',
        label: '累计入库',
        icon: new URL('./img/e4.png', import.meta.url).href,
        af: '0',
        mf: '0',
    },
    {
        key: 'match',
        label: '进度匹配率',
        icon: new URL('./img/e5.png', import.meta.url).href,
        af: '100%',
        mf: '100%',
    },
    {
        key: 'bias',
        label: '进度偏差量',
        icon: new URL('./img/e6.png', import.meta.url).href,
        af: '0',
        mf: '0',
    },
    {
        key: 'max-in',
        label: '最高入库日',
        icon: new URL('./img/e7.png', import.meta.url).href,
        af: '2024-06-10|0',
        mf: '2024-06-12|0',
    },
    {
        key: 'min-in',
        label: '最低入库日',
        icon: new URL('./img/e8.png', import.meta.url).href,
        af: '2024-06-02|0',
        mf: '2024-06-03|0',
    },
]);
// 计算当前时间减去14小时
const getDate = () => {
    const now = new Date();
    now.setTime(now.getTime() - 14 * 60 * 60 * 1000);
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 获取URL参数中的date
function getUrlDate() {
    // 支持 ?date=xxxx-xx-xx 或 #/xxx?date=xxxx-xx-xx
    const search = window.location.search || '';
    const hash = window.location.hash || '';
    let match = search.match(/[?&]date=([0-9]{4}-[0-9]{2}-[0-9]{2})/);
    if (!match && hash) {
        match = hash.match(/[?&]date=([0-9]{4}-[0-9]{2}-[0-9]{2})/);
    }
    return match ? match[1] : '';
}

const urlDate = getUrlDate();

onMounted(() => {
    // 获取接口数据
    getListData()
    // ...nextTick等原有代码
});

const getListData = () => {
    let date = urlDate || getDate()
    getDateList({ date: date }).then(res => {
        if (res.code === 200) {
            const af = res.result.filter(x=>x.tenantId==8050)[0];
            const mf = res.result.filter(x=>x.tenantId==8080)[0];
            summaryList.find(i => i.key === 'target-out').af = af?.monthlyOutboundTarget || 0;
            summaryList.find(i => i.key === 'target-in').af = af?.monthlyInboundTarget || 0;
            summaryList.find(i => i.key === 'out').af = af?.totalOutbound || 0;
            summaryList.find(i => i.key === 'in').af = af?.totalInbound || 0;
            summaryList.find(i => i.key === 'match').af = af?.productionProgressMatchRate || '0.00%';
            summaryList.find(i => i.key === 'bias').af = af?.productionProgressDeviation || 0;
            summaryList.find(i => i.key === 'max-in').af = af?.monthlyMaxInbound.replace(' / ', '<br>') || '~';
            summaryList.find(i => i.key === 'min-in').af = af?.monthlyMinInbound.replace(' / ', '<br>') || '~';

            summaryList.find(i => i.key === 'target-out').mf = mf?.monthlyOutboundTarget || 0;
            summaryList.find(i => i.key === 'target-in').mf = mf?.monthlyInboundTarget || 0;
            summaryList.find(i => i.key === 'out').mf = mf?.totalOutbound || 0;
            summaryList.find(i => i.key === 'in').mf = mf?.totalInbound || 0;
            summaryList.find(i => i.key === 'match').mf = mf?.productionProgressMatchRate || '0.00%';
            summaryList.find(i => i.key === 'bias').mf = mf?.productionProgressDeviation || 0;
            summaryList.find(i => i.key === 'max-in').mf = mf?.monthlyMaxInbound.replace(' / ', '<br>') || '~';
            summaryList.find(i => i.key === 'min-in').mf = mf?.monthlyMinInbound.replace(' / ', '<br>') || '~';
        }
    }).catch(err => {
        console.error('getDateList error:', err);
    });
};
</script>

<style scoped lang="scss">
.af{
  color:#007AFF !important;
}
.mf{
  color:#4caf50 !important;
}
.summary-container {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 4px 18px rgba(0, 0, 0, 0.08);
    padding: 0 0 24px 0;
    margin: 0;
    max-width: 100%;
    margin: 0 auto;
    width: 100%;
    box-sizing: border-box;
}

@media (max-width: 1200px) {
    .summary-container {
        max-width: 100%;
        width: 100%;
        margin: 16px auto;
        border-radius: 12px;
        padding: 0 0 12px 0;
    }
}

@media (max-width: 900px) {
    .summary-container {
        max-width: 100%;
        width: 100%;
        margin: 0;
        border-radius: 0;
        box-shadow: none;
        padding: 0 0 4px 0;
    }
    .summary-table {
        width: 100vw;
        min-width: 0;
        overflow-x: auto;
        display: block;
    }
    .summary-row {
        font-size: 13px;
        min-height: 32px;
    }
    .summary-col {
        min-width: 90px;
        padding: 6px 4px;
    }
}

@media (max-width: 600px) {
    .summary-container {
        max-width: 100%;
        width: 100%;
        margin: 0;
        border-radius: 0;
        box-shadow: none;
        padding: 0 0 4px 0;
    }
}

.summary-header {
    position: relative;
    padding: 18px 24px 12px 24px;
    background: none;
    background-image: url('./img/AFMF.png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    min-height: 100px;
    display: flex;
    align-items: center;
}

.summary-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
}

.summary-title-img {
    width: 18px;
    height: 18px;
    object-fit: contain;
    margin-right: 8px;
    vertical-align: middle;
}

.summary-bg {
    position: absolute;
    right: 16px;
    top: 0;
    height: 60px;
    z-index: 1;
    pointer-events: none;
}

.summary-table {
    width: 100%;
    overflow-x: auto;
    display: block;
    margin: 0 auto;
    box-sizing: border-box;
}

.summary-row {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    min-height: 48px;
    font-size: 16px;
    background: none;
}

.summary-row:last-child {
    border-bottom: none;
}

.summary-row-header {
    background: #f7f8fa;
    font-weight: bold;
    font-size: 16px;
}

.summary-col {
    flex: 1 1 0;
    padding: 8px 10px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    min-width: 0;
    box-sizing: border-box;
    word-break: break-all;
}

.summary-col-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    min-width: 0;
}

.summary-col-af {
    color: #222;
    justify-content: center;
    text-align: center;
    font-weight: normal;
}

.summary-col-mf {
    justify-content: center;
    text-align: center;
    font-weight: normal;
}

.summary-icon {
    width: 28px;
    height: 28px;
    margin-right: 5px;
    object-fit: contain;
}

.summary-label {
    font-size: 16px;
    color: #222;
    margin-left: 8px;
    word-break: break-all;
    overflow-wrap: break-word;
    white-space: normal;
    flex: 1 1 0;
}

.summary-row,
.summary-col {
    min-width: 0;
    word-break: break-all;
    flex-wrap: wrap;
}

.num {
    font-weight: 600;
}

.unit {
    font-size: 12px;
    margin-left: 4px;
    vertical-align: baseline;
    margin: -3px 0 0 4px;
    font-weight: normal;
}

@media (max-width: 768px) {
    .summary-container {
        max-width: 100%;
        border-radius: 10px;
        padding: 0;
        margin-bottom: 20px;
    }

    .summary-header {
        padding: 12px 10px 8px 10px;
        min-height: 60px;
    }

    .summary-title {
        font-size: 16px;
    }

    .summary-bg {
        height: 36px;
        right: 4px;
    }

    .summary-row {
        font-size: 14px;
        min-height: 36px;
    }

    .summary-icon {
        width: 24px;
        height: 24px;
        margin-right: -2px;
    }

    .summary-label {
        font-size: 13px;
    }

    .unit {
        font-size: 12px;
        margin-left: 4px;
        vertical-align: baseline;
        margin: -3px 0 0 2px;
    }
}
</style>

<style>
.num {
  font-weight: 600;
}
</style>
